Page({
  data: {
    title:'',
    startDate: '',
    endDate: '',
    selectedDate: '',
    countdownArray: [
      { label: '天', value: '00' },
      { label: '时', value: '00' },
      { label: '分', value: '00' },
      { label: '秒', value: '00' }
    ],
    isCounting: false,
    countdownTimer: null,
    targetDate: '',
    history: []
  },

  onLoad: function() {
    this.setData({
      title:wx.getStorageSync('alarmTitle')
    })
    console.log(wx.getStorageSync('alarmTitle'))
    // wx.setStorageSync('alarmTitle', e.detail.value)
    // 初始化日期范围
    this.initDateRange();
    
    // 从缓存中获取历史记录
    this.loadHistory();
    
    // 从缓存中获取已保存的倒计时
    this.loadSavedCountdown();
  },
  onc(e){
    this.setData({
      title:e.detail.value
    })
    wx.setStorageSync('alarmTitle', e.detail.value)
    console.log(e.detail.value)
  },
  // 初始化日期范围
  initDateRange: function() {
    const today = new Date();
    const oneYearLater = new Date();
    oneYearLater.setFullYear(today.getFullYear() + 1);
    
    const startDate = this.formatDate(today);
    const endDate = this.formatDate(oneYearLater);
    
    this.setData({
      startDate: startDate,
      endDate: endDate,
      selectedDate: startDate
    });
  },

  // 日期格式化
  formatDate: function(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 日期选择变化
  onDateChange: function(e) {
    this.setData({
      selectedDate: e.detail.value
    });
  },

  // 开始倒计时
  startCountdown: function() {
    const selectedDate = this.data.selectedDate;
    if (!selectedDate) {
      wx.showToast({
        title: '请选择目标日期',
        icon: 'none'
      });
      return;
    }
    
    // 保存到历史记录
    this.saveToHistory(selectedDate);
    
    // 设置目标日期
    this.setData({
      targetDate: selectedDate,
      isCounting: true
    });
    
    // 开始倒计时
    this.startCountdownTimer();
    
    // 保存到缓存
    this.saveCountdownToStorage(selectedDate);
    
    wx.showToast({
      title: '倒计时已开始',
      icon: 'success'
    });
  },

  // 开始倒计时计时器
  startCountdownTimer: function() {
    const that = this;
    if (this.data.countdownTimer) {
      clearInterval(this.data.countdownTimer);
    }
    
    this.data.countdownTimer = setInterval(function() {
      that.calculateCountdown();
    }, 1000);
  },

  // 计算倒计时
  calculateCountdown: function() {
    const targetDate = this.data.targetDate;
    if (!targetDate) return;
    
    const now = new Date();
    const target = new Date(targetDate);
    
    // 确保目标日期在当前日期之后
    if (target <= now) {
      this.setData({
        countdownArray: [
          { label: '天', value: '00' },
          { label: '时', value: '00' },
          { label: '分', value: '00' },
          { label: '秒', value: '00' }
        ],
        isCounting: false
      });
      clearInterval(this.data.countdownTimer);
      wx.showToast({
        title: '倒计时已结束',
        icon: 'none'
      });
      return;
    }
    
    // 计算时间差（毫秒）
    const diff = target - now;
    
    // 计算天、时、分、秒
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((diff % (1000 * 60)) / 1000);
    
    // 更新倒计时显示
    this.setData({
      countdownArray: [
        { label: '天', value: days.toString().padStart(2, '0') },
        { label: '时', value: hours.toString().padStart(2, '0') },
        { label: '分', value: minutes.toString().padStart(2, '0') },
        { label: '秒', value: seconds.toString().padStart(2, '0') }
      ]
    });
  },

  // 清除倒计时
  clearCountdown: function() {
    if (this.data.isCounting) {
      clearInterval(this.data.countdownTimer);
      this.setData({
        isCounting: false,
        targetDate: '',
        countdownArray: [
          { label: '天', value: '00' },
          { label: '时', value: '00' },
          { label: '分', value: '00' },
          { label: '秒', value: '00' }
        ]
      });
      
      // 清除缓存
      wx.removeStorage({
        key: 'countdownTargetDate',
        success: function() {
          wx.showToast({
            title: '倒计时已清除',
            icon: 'success'
          });
        }
      });
    } else {
      wx.showToast({
        title: '当前没有正在进行的倒计时',
        icon: 'none'
      });
    }
  },

  // 保存倒计时到缓存
  saveCountdownToStorage: function(date) {
    wx.setStorage({
      key: 'countdownTargetDate',
      data: date
    });
  },

  // 从缓存加载保存的倒计时
  loadSavedCountdown: function() {
    wx.getStorage({
      key: 'countdownTargetDate',
      success: (res) => {
        this.setData({
          targetDate: res.data,
          selectedDate: res.data
        });
        if (!this.data.isCounting) {
          this.startCountdownTimer();
        }
      },
      fail: () => {
        // 没有保存的倒计时
      }
    });
  },

  // 保存到历史记录
  saveToHistory: function(date) {
    let history = this.data.history;
    const now = new Date();
    const formattedNow = this.formatDate(now);
    
    // 计算剩余时间
    const target = new Date(date);
    const nowDate = new Date();
    const diff = target - nowDate;
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const remaining = days > 0 ? `${days}天` : '已过期';
    
    // 添加到历史记录
    history.unshift({
      date: formattedNow,
      targetDate: date,
      remaining: remaining
    });
    
    // 限制历史记录数量
    if (history.length > 10) {
      history = history.slice(0, 10);
    }
    
    this.setData({
      history: history
    });
    
    // 保存到缓存
    wx.setStorage({
      key: 'countdownHistory',
      data: history
    });
  },

  // 加载历史记录
  loadHistory: function() {
    wx.getStorage({
      key: 'countdownHistory',
      success: (res) => {
        this.setData({
          history: res.data
        });
      },
      fail: () => {
        // 没有历史记录
      }
    });
  },

  // 加载历史倒计时
  loadHistoryCountdown: function(e) {
    const index = e.currentTarget.dataset.index;
    const historyItem = this.data.history[index];
    
    this.setData({
      selectedDate: historyItem.targetDate
    });
    
    wx.showToast({
      title: '已加载历史倒计时',
      icon: 'success'
    });
  },

  onUnload: function() {
    // 页面卸载时清除计时器
    if (this.data.countdownTimer) {
      clearInterval(this.data.countdownTimer);
    }
  }
});